package com.cgtong.android.http;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SPUtils;
import com.google.gson.Gson;
import com.zhouyou.http.interceptor.BaseExpiredInterceptor;
import com.zhouyou.http.model.ApiResult;

import org.simple.eventbus.EventBus;

import okhttp3.Response;

public class TokenInterceptor extends BaseExpiredInterceptor {
    private ApiResult apiResult;

    @Override
    public boolean isResponseExpired(Response response, String bodyString) {
        if (!SPUtils.getInstance().getBoolean(ConstantManager.FIRST_TOKEN_VALIDATE)) {
            apiResult = new Gson().fromJson(bodyString, ApiResult.class);
            if (apiResult != null) {
                int code = apiResult.getCode();
                if (code == ConstantManager.ACCESS_TOKEN_EXPIRED
                        || code == ConstantManager.ACCESS_USER_FORBIDDEN) {
                    return true;
                }
            }
        }
        return false;
    }

    //只有上面配置的过期情况才会执行这里
    @Override
    public Response responseExpired(Chain chain, String bodyString) {
        try {
            if (!SPUtils.getInstance().getBoolean(ConstantManager.FIRST_TOKEN_VALIDATE)) {  //不是应用启动首次验证token
                switch (apiResult.getCode()) {
                    case ConstantManager.ACCESS_TOKEN_EXPIRED: //AccessToken已过期
                        LogUtils.e("------------------token失效------------------");
                        EventBus.getDefault().post(ConstantManager.RELOGIN_CODE_EXPIRED, ConstantManager.RELOGIN_TAG);
                        break;
                    case ConstantManager.ACCESS_USER_FORBIDDEN: //用户被禁用
                        LogUtils.e("------------------用户被禁用------------------");
                        EventBus.getDefault().post(ConstantManager.RELOGIN_CODE_FORBIDDEN, ConstantManager.RELOGIN_TAG);
                        break;
                    default:
                        break;
                }
            }
            return chain.proceed(chain.request());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    //同步请求refreshToken
//    public void refreshToken() throws IOException {
//        EasyHttp.post(ComParamContact.Token.PATH)
//                .params(ComParamContact.Common.REFRESH_TOKEN, TokenManager.getInstance().getAuthModel().getRefreshToken())
//                .sign(false)
//                .accessToken(false)
//                .timeStamp(true)
//                .syncRequest(true)//同步请求
//                .execute(new SimpleCallBack<AuthModel>() {
//                    @Override
//                    public void onError(ApiException e) {
//                    }
//
//                    @Override
//                    public void onSuccess(AuthModel response) {
//                    }
//                });
//    }

}